import React, { useEffect, useState, useMemo } from 'react';
import { Input, Tree } from 'antd';
const { Search } = Input;

let requestData = [
  {
    "id": 101,
    "name": "深圳总公司",
    "parentId": 100
  },
  {
    "id": 103,
    "name": "研发部门",
    "parentId": 101
  },
  {
    "id": 108,
    "name": "市场部门",
    "parentId": 102
  },
  {
    "id": 100,
    "name": "小星星集团有限公司",
    "parentId": 0
  },
  {
    "id": 102,
    "name": "长沙分公司",
    "parentId": 100
  },
  {
    "id": 104,
    "name": "市场部门",
    "parentId": 101
  },
  {
    "id": 109,
    "name": "财务部门",
    "parentId": 102
  },
  {
    "id": 105,
    "name": "测试部门",
    "parentId": 101
  },
  {
    "id": 106,
    "name": "财务部门",
    "parentId": 101
  },
  {
    "id": 107,
    "name": "运维部门",
    "parentId": 101
  }
];

const TreeBox = ({onSelect}) => {
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [treeData, setTreeData] = useState([]);

  useEffect(() => {
    const idMap = new Map();

    // 映射所有节点
    requestData.forEach(item => {
      idMap.set(item.id, {
        title: item.name,
        key: item.id.toString(),
        children: []
      });
    });

    // 提取根节点
    const treeLists = [];
    requestData.forEach(item => {
      if (item.parentId === 0) {
        treeLists.push(idMap.get(item.id));
      } else {
        const parent = idMap.get(item.parentId);
        if (parent) {
          parent.children.push(idMap.get(item.id));
        }
      }
    });

    // 初始化数据
    setTreeData(treeLists);

    console.log(treeLists); // 检查输出
  }, []);

  const onExpand = (newExpandedKeys) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e) => {
    const { value } = e.target;
    const newExpandedKeys = treeData
      .flatMap((item) => {
        if (item.title.includes(value)) {
          return [item.key];
        }
        return item.children
          ? item.children.flatMap((child) => {
              if (child.title.includes(value)) {
                return [child.key];
              }
              return [];
            })
          : [];
      })
      .filter((item, i, self) => !!(item && self.indexOf(item) === i));
    setExpandedKeys(newExpandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
  };
  
  const treeDataFiltered = useMemo(() => {
    const loop = (data) =>
      data.map((item) => {
        const strTitle = item.title;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span key={item.key}>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span key={item.key}>{strTitle}</span>
          );
        if (item.children) {
          return {
            title,
            key: item.key,
            children: loop(item.children),
          };
        }
        return {
          title,
          key: item.key,
        };
      });
    return loop(treeData);
  }, [searchValue, treeData]);
  const onNodeSelect = (selectedKeys) => {
    onSelect(selectedKeys); // 调用父组件传入的回调函数
  };
  return (
    <div>
      <Search
        style={{
          marginBottom: 8,
        }}
        placeholder="Search"
        onChange={onChange}
      />
      <Tree
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        treeData={treeDataFiltered}
        defaultExpandAll={true}
        onSelect={onNodeSelect}
      />
    </div>
  );
};

export default TreeBox;